<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('create', 'captcha'),
				'users'=>array('*'),
			),
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('view','update', 'password', 'index', 'databasecleanup'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
	}
	
	/**
	* Displays a particular model.
	*/
	public function actionIndex()
	{
		$this->pageTitle = Yii::t('title', 'User options');
		
		$model = User::model()->findByPk(Yii::app()->user->getId());
		
		$condition = new CDbCriteria();
		$condition->addCondition('user = "' . $model->id . '"');
		$entryCount = History::model()->count($condition);
		$overallEntryCount = History::model()->count();
		
		$this->render('index', 
			array(
				'model' => $model,
				'entryCount' => $entryCount,
				'overallEntryCount' => $overallEntryCount
			)
		);
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$this->pageTitle = Yii::t('title', 'Register');
		
		$model=new User;
		$model->scenario = 'register';

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->created = date("Y-m-d G:i:s");
			$model->id = uniqid();
			
			$model->salt = $model->getSalt(15);
			$model->password = $model->hashPassword($model->password1);
			
			if ($model->save()) {
				Yii::app()->user->setFlash('success', Yii::t('controller', 'Registration successful'));
			
				$this->redirect(array('/site/login','id'=>$model->id));
			}	
		}
		
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		$this->pageTitle = Yii::t('title', 'Update your personal information');
		
		$model=$this->loadModel();
		$model->scenario = 'update';
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->edited = date("Y-m-d G:i:s");
			
			if ($model->save()) {
				Yii::app()->user->setFlash('success', Yii::t('controller', 'Personal information successfully updated'));
				$this->redirect(array('index'));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionPassword()
	{
		$this->pageTitle = Yii::t('title', 'Change your password');

		$model=$this->loadModel();
		$model->scenario = 'changepassword';

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->edited = date("Y-m-d G:i:s");
			
			$model->salt = $model->getSalt(15);
			$model->password = $model->hashPassword($model->password1);
			
			if ($model->save()) {
				Yii::app()->user->setFlash('success', Yii::t('controller', 'Password successfully changed'));
				$this->redirect(array('index'));
			}
		}

		$this->render('password',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionDatabaseCleanUp()
	{
		$condition = new CDbCriteria();
		$condition->addCondition('user = "' . Yii::app()->user->getId() . '"');
		
		History::model()->deleteAll($condition);
		
		Yii::app()->user->setFlash('success', Yii::t('controller', 'Database cleanup complete'));
		$this->redirect(array('index'));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		$model=User::model()->findByPk(Yii::app()->user->getId());
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
